package com.manjason.property.dao.impl;

import com.manjason.property.dao.PropertyDao;
import com.manjason.property.entity.Property;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.io.Serializable;
import java.util.List;

public class PropertyDaoImpl implements PropertyDao {

    private static final SessionFactory ourSessionFactory;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            ourSessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }

    @Override
    public Property findPropertyEntityByPlayerName(String playerName) {
        String hql = " from Property where playerName=:playerName";
        Query query = getSession().createQuery(hql);
        query.setString("playerName", playerName);
        query.setMaxResults(1);
        return (Property) query.uniqueResult();
    }

    @Override
    public void saveOrUpdate(Property entity) {
        Session session = getSession();
        try {
            session.beginTransaction();
            session.saveOrUpdate(entity);
            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }

    }

    @Override
    public void update(Property entity) {
        getSession().update(entity);
    }

    @Override
    public void delete(Property entity) {
        getSession().delete(entity);
    }

    @Override
    public Property findObjectById(Serializable id) {
        return getSession().get(Property.class, id);
    }

    @Override
    public List<Property> findObjects() {
        String hql = " from Property";
        Query query = getSession().createQuery(hql);
        return query.list();
    }
}
